function updateCartItem(pid, quantity) {
    var cartContent = localStorage.getItem("ierg4210_cart");
    if (cartContent) {
        cartContent = JSON.parse(cartContent);
    } else {
        cartContent = {};
    }
    cartContent[pid] = quantity < 0 ? 0 : quantity;
    localStorage.setItem("ierg4210_cart", JSON.stringify(cartContent));
}

function updateProdutPrice(pid, price) {
    var productPrices = localStorage.getItem("ierg4210_price");
    if (productPrices) {
        productPrices = JSON.parse(productPrices);
    } else {
        productPrices = {};
    }
    productPrices[pid] = price;
    localStorage.setItem("ierg4210_price", JSON.stringify(productPrices));
}

function updateTotalval() {
    var totalVal = 0.00;
    var cartContent = localStorage.getItem("ierg4210_cart");
    var productPrices = localStorage.getItem("ierg4210_price");
    if (cartContent && productPrices) {
        productPrices = JSON.parse(productPrices);
        cartContent = JSON.parse(cartContent);
        for (var key in cartContent) {
            var quantity = cartContent[key];
            if (quantity > 0) {
                var price = productPrices[key];
                totalVal += (parseInt(quantity) * parseFloat(price));
            }
        }
    }
    document.querySelector("#total_cost").innerHTML = Number(totalVal).toFixed(2);
}
function queryProduct(pid, quantity) {

    if (quantity <= 0) {
        return function () {
        };
    }

    var li = document.createElement("li");

    var name = document.createElement("p");
    name.setAttribute("class", "shopping_product_name");
    li.appendChild(name);

    var num = document.createElement("p");
    num.setAttribute("class", "shopping_product_num");
    var numInput = document.createElement("input");
    numInput.setAttribute("class", "shopping_product_quantity");
    numInput.setAttribute("type", "number");
    numInput.setAttribute("name", "quantity");
    numInput.setAttribute("min", 0);
    numInput.setAttribute("value", quantity);
    num.appendChild(numInput);

    var increaseBtn = document.createElement("input");
    increaseBtn.setAttribute("type", "button");
    increaseBtn.setAttribute("class", "cart_num_btn");
    increaseBtn.value = "+";
    num.appendChild(increaseBtn);

    var decreaseBtn = document.createElement("input");
    decreaseBtn.setAttribute("type", "button");
    increaseBtn.setAttribute("class", "cart_num_btn");
    decreaseBtn.value = "-";
    num.appendChild(decreaseBtn);

    li.appendChild(num);

    var cost = document.createElement("p");
    cost.setAttribute("class", "shopping_product_cost");
    li.appendChild(cost);

    document.getElementById("shopping_list").appendChild(li);

    return function query() {
        console.log("queryProduct :pid " + pid + "; quantity: " + quantity);
        if (quantity <= 0) {
            return;
        }

        myLib.simplePostAjax(opt = {
            data: "pid=" + pid,
            url: "../phps/product_query_handler.php",
            withCredentials: "true",
            success: function (response) {
                result = JSON.parse(response);
                if (result.success) {

                    name.innerHTML = result.success.name;

                    var productPrice = parseFloat(result.success.price);
                    var costVal = Number(parseInt(quantity) * productPrice).toFixed(2);
                    cost.innerHTML = "HK$ " + costVal;

                    updateProdutPrice(pid, result.success.price);

                    increaseBtn.onclick = function () {
                        numInput.value = parseInt(numInput.value) + 1;
                        numInput.onchange();
                    }

                    decreaseBtn.onclick = function () {
                        numInput.value = parseInt(numInput.value) - 1;
                        numInput.onchange();
                    }

                    numInput.onchange = function (e) {
                        var currentQuantity = parseInt(this.value);

                        cost.innerHTML = "HK$ " + Number(currentQuantity * productPrice).toFixed(2);
                        updateCartItem(pid, currentQuantity);
                        if (currentQuantity <= 0) {
                            document.getElementById("shopping_list").removeChild(li);
                        }
                        updateTotalval();
                    }


                    updateTotalval();

                } else {
                    alert("Error : " + result.failed);
                }

            }
        });
    }
}

function clearCartView() {
    var cartlist = document.getElementById("shopping_list");
    while (cartlist.firstChild) {
        cartlist.removeChild(cartlist.firstChild);
    }
}

function refreshCart() {
    clearCartView();

    var cartContent = localStorage.getItem("ierg4210_cart");
    if (cartContent) {
        cartContent = JSON.parse(cartContent);
        for (var key in cartContent) {
            var quantity = cartContent[key];
            console.log("inside cartContent loop : " + key + " : " + quantity);
            var query = queryProduct(key, quantity);
            query();
        }
    }
}


function addToCart(pid) {

    return function add() {
        console.log("Start add pid " + pid);
        var cartContent = localStorage.getItem("ierg4210_cart");
        if (cartContent) {
            cartContent = JSON.parse(cartContent);
        } else {
            cartContent = {};
        }
        if (cartContent[pid]) {
            cartContent[pid] = cartContent[pid] + 1;
        } else {
            cartContent[pid] = 1;
        }
        localStorage.setItem("ierg4210_cart", JSON.stringify(cartContent));
        console.log("Finish add pid " + pid);

        refreshCart();
    }

}


function checkOutToServer() {
    var cartContent = localStorage.getItem("ierg4210_cart");
    if (cartContent) {
        cartContent = JSON.parse(cartContent);
        submitCart = {};
        for (var key in cartContent) {
            var quantity = cartContent[key];
            if (quantity > 0) {
                submitCart[key] = quantity;
            }
        }
        submitCartJson = JSON.stringify(submitCart);

        myLib.simplePostAjax(opt = {
                data: "cart_items=" + submitCartJson + "&cart_token=" + document.querySelector("#cart_token").value,
                url: "../phps/cart_handler.php",
                success: function (response) {
                    result = JSON.parse(response);
                    if (result.success) {
                        //TODO
                        //alert("check out result: " + result.success.digest + "  ; oid = " + result.success.order_id);
                        var shoppingForm = document.querySelector("#shopping_cart_form");

                        var customField = document.createElement("input");
                        customField.setAttribute("type", "hidden");
                        customField.setAttribute("name", "custom");
                        customField.setAttribute("value", result.success.digest);
                        shoppingForm.appendChild(customField);

                        var invoiceField = document.createElement("input");
                        invoiceField.setAttribute("type", "hidden");
                        invoiceField.setAttribute("name", "invoice");
                        invoiceField.setAttribute("value", result.success.order_id);
                        shoppingForm.appendChild(invoiceField);

                        var charsetField = document.createElement("input");
                        charsetField.setAttribute("type", "hidden");
                        charsetField.setAttribute("name", "charset");
                        charsetField.setAttribute("value", result.success.charset);
                        shoppingForm.appendChild(charsetField);

                        var currencyField = document.createElement("input");
                        currencyField.setAttribute("type", "hidden");
                        currencyField.setAttribute("name", "currency_code");
                        currencyField.setAttribute("value", result.success.currency_code);
                        shoppingForm.appendChild(currencyField);

                        var merchantField = document.createElement("input");
                        merchantField.setAttribute("type", "hidden");
                        merchantField.setAttribute("name", "business");
                        merchantField.setAttribute("value", result.success.merchant_email);
                        shoppingForm.appendChild(merchantField);

                        var cart_details = JSON.parse(result.success.cart_details);
                        let counter = 1;
                        for (pid in cart_details) {
                            let itemField = document.createElement("input");
                            itemField.setAttribute("name", "item_name_" + counter);
                            itemField.setAttribute("type", "hidden");
                            itemField.setAttribute("value", cart_details[pid]['name']);
                            shoppingForm.appendChild(itemField);

                            let pidField = document.createElement("input");
                            pidField.setAttribute("name", "item_number_" + counter);
                            pidField.setAttribute("type", "hidden");
                            pidField.setAttribute("value", pid);
                            shoppingForm.appendChild(pidField);

                            let quantityField = document.createElement("input");
                            quantityField.setAttribute("name", "quantity_" + counter);
                            quantityField.setAttribute("value", cart_details[pid]['quantity']);
                            quantityField.setAttribute("type", "hidden");
                            shoppingForm.appendChild(quantityField);

                            let priceField = document.createElement("input");
                            priceField.setAttribute("name", "amount_" + counter);
                            priceField.setAttribute("value", cart_details[pid]['price']);
                            priceField.setAttribute("type", "hidden");
                            shoppingForm.appendChild(priceField);

                            counter++;
                        }

                        localStorage.clear();

                        shoppingForm.submit();
                    } else {
                        //TODO
                        alert("Fail " + result.failed);
                    }
                }
            }
        );
    }
    else {
        //shopping cart is empty
        alert("Your shopping cart is empty. Why not add some products ?");
    }

}

document.querySelector("#checkout_button").onclick = function (e) {
    // alert("Checking out !")
    checkOutToServer();
}

document.querySelector("#shopping_cart_form").addEventListener('keypress', function (event) {
    if (event.keyCode == 13) {
        event.preventDefault();
        document.querySelector("#checkout_button").focus();
    }
}, false);

refreshCart();